




var channel_id = '';
var max_id = 0;
/* channel_id can change in time. beware of it. */
function generate_channel_id_updater(iframe_uri, username, user_comet_callback){
    var username = username;
    var gc = null;
    var update_scheduled = false;
    
    /* comet callback function */
    function comet_callback(data) {
        var a      = data.split(' ');
        var id     = a[0];
        var author = a[1];
        
        /* system messages */
        if(id == 'connected')
            return;
        if(id == 'ping')
            return;
        if(id == 'destroyed'){ // this channel_id is no longer valid, get new channel_id
            update_channel_id();
            return;
        }
        
        id = Number(id);
        /* ignore duplicate events */
        if(id <= max_id)
            return;
        max_id = id;
        user_comet_callback(id, author, a.slice(2).join(' ') );
    }
    
    function get_comet_uri(){
        return('/comet/'+ channel_id + '/listen?z='+Math.random() +'&last_eventid=' + max_id + '&username=' + username );
    }
    
    function update_channel_id() {
        var xhr;
        function ajax_callback(){
            if(xhr.readyState != 4)
                return;
            if(xhr.status != 200){
                setTimeout(update_channel_id, 1000*30);
                update_scheduled = false;
                return;
            }
            var r = false;
            if(xhr.responseText){
                var j = eval('(' + xhr.responseText + ')');// json here
                if(channel_id != j.channel_id){
                    r = true;
                    channel_id = j.channel_id;
                    max_id     = j.last_event_id;
                }
                /**/
                user_channel_callback( (channel_id != j.channel_id) , j);
            }
            if(r){
                if(gc)
                    gc();
                gc = comet_schedule_crossdomain(iframe_uri, get_comet_uri, comet_callback);
            }
            update_scheduled = false;
        };
        if(update_scheduled)
            return;
        if(xhr)
            xhr.abort();
        xhr = create_xhr();
        xhr.onreadystatechange = ajax_callback;
        xhr.open('GET', './channel_uri?a=' + Math.random(), true);
        xhr.send(null);
        update_scheduled = true;
    }
    update_channel_id();
    return update_channel_id;
}



